package com.czy.owner.ui.collection;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.czy.otherlib.swipetoloadlayout.OnLoadMoreListener;
import com.czy.otherlib.swipetoloadlayout.OnRefreshListener;
import com.czy.otherlib.swipetoloadlayout.SwipeToLoadLayout;
import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.UserCollectInfoAdapter;
import com.czy.owner.api.CollectionApi;
import com.czy.owner.api.UserCollectInfoApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.UserCollectInfoModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.information.InformationDetailActivity;
import com.czy.owner.utils.PhoneUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by wangyang on 2017/5/16 0016.
 * 攻略收藏
 */

public class StrategyCollectionFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    @BindView(R.id.ll_tip)
    LinearLayout llTip;
    @BindView(R.id.refresh_target)
    RecyclerView recyclerView;
    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;
    private List<UserCollectInfoModel.ListBean> list = new ArrayList<>();
    private List<UserCollectInfoModel.ListBean> myList = new ArrayList<>();
    private UserCollectInfoAdapter adapter;
    private int page = 1;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_user_collect_info;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        RxBus.getDefault().register(this);
        adapter = new UserCollectInfoAdapter(getActivity(), list, true, false);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        swipeToLoadLayout.setRefreshing(true);
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);

        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<UserCollectInfoModel.ListBean>() {
            @Override
            public void onItemClick(int position, UserCollectInfoModel.ListBean model, View view) {
                Intent ti = new Intent(getActivity(), InformationDetailActivity.class);
                ti.putExtra("title", model.getTitle());
                ti.putExtra("content", model.getContent());
                ti.putExtra("imgUrl", model.getCoverUrl());
                ti.putExtra("infoId", model.getInfoId());
                ti.putExtra("isCollect", true);
                ti.putExtra("collectType", "strategy");
                ti.putExtra("mType", "strategyCollectList");
                startActivity(ti);
            }
        });

        adapter.setDeleteListener(new UserCollectInfoAdapter.DeletedListener() {
            @Override
            public void onClick(View v, int position, List<UserCollectInfoModel.ListBean> data) {
                requestCollect("strategy", data.get(position).getInfoId() + "", "delCollect",position);
            }
        });

    }

    @Override
    protected void updateViews() {
        getDataList();
    }

    private void getDataList() {
        UserCollectInfoApi userCollectInfoApi = new UserCollectInfoApi(new HttpOnNextListener<UserCollectInfoModel>() {
            @Override
            public void onNext(UserCollectInfoModel model) {
                setDataList(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<UserCollectInfoModel>>() {
                }.getType();
                BaseResultEntity<UserCollectInfoModel> cacheList = gson.fromJson(cache, type);
                setDataList(cacheList.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
                swipeToLoadLayout.setRefreshing(false);
                swipeToLoadLayout.setLoadingMore(false);
            }
        }, (RxAppCompatActivity) (getContext()), page + "","strategy");
        userCollectInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        userCollectInfoApi.setPage(page + "");
        userCollectInfoApi.setSize("10");
        userCollectInfoApi.setType("strategy");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(userCollectInfoApi);
    }

    private void setDataList(UserCollectInfoModel model) {

        if (page == 1) {
            myList = model.getList();
        } else {
            myList.addAll(list);
        }
        adapter.setList(myList);
        checkTips();
        swipeToLoadLayout.setRefreshing(false);
        swipeToLoadLayout.setLoadingMore(false);
    }

    private void checkTips() {
        if (adapter.getItemCount()!=0) {
            llTip.setVisibility(View.GONE);
        } else {
            llTip.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onLoadMore() {
        page++;
        getDataList();
    }

    @Override
    public void onRefresh() {
        swipeToLoadLayout.setLoadMoreEnabled(true);
        page = 1;
        getDataList();
    }

    private void requestCollect(String collectType,String collectTypeId, String type,final int position) {
        CollectionApi collectionApi = new CollectionApi(new HttpOnNextListener<String>() {
            @Override
            public void onNext(String o) {
                adapter.removeData(position);
                checkTips();
//                RxBus.getDefault().post(Constants.COLLECTION, new CommonEvent("strategyCollectList", -1, false));
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }
        }, (RxAppCompatActivity) getContext());
        collectionApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        collectionApi.setCollectType(collectType);
        collectionApi.setCollectTypeId(collectTypeId);
        collectionApi.setType(type);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(collectionApi);
    }

    @Subscribe(code = Constants.COLLECTION, threadMode = ThreadMode.MAIN)
    public void collection(CommonEvent event) {
        if(event.getMsg().equals("strategy")){
            onRefresh();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }
}
